import axios, {
  AxiosError,
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
} from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
import qs from 'qs'
import type { IOResponse } from './types'
interface IOParams {
  [key: string]: string | number
}
class AxiosHttp {
  axiosInstance: AxiosInstance
  config: AxiosRequestConfig
  constructor(config: AxiosRequestConfig) {
    this.axiosInstance = axios.create(config)
    this.config = config
    this.axiosInstance.interceptors.request.use(
      (config) => {
        // if (config.data instanceof FormData) {
        //   config.headers['Content-Type'] = 'multipart/formdata'
        // }
        const userStore = useUserStore()
        if (config.data) {
          config.data.orgId = config.data.orgId || userStore.userInfo.orgId
          // config.data.orgName = userStore.userInfo.orgName
        }
        config.headers['Stoken'] = userStore.getToken
        if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
          config.data = qs.stringify(config.data)
        }
        return config
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      },
    )
    this.axiosInstance.interceptors.response.use(
      (response: AxiosResponse) => {
        if (response) {
          const data = response.data
          if (data.code === '401') {
            ElMessage({
              type: 'error',
              message: '用户未认证，请重新登陆!',
            })
            const userStore = useUserStore()
            userStore.$reset()
            localStorage.removeItem('userInfo')
          }
          if (data.code === '500') {
            ElMessage({
              type: 'error',
              message: data.msg,
            })
          }
          return data
        } else {
          return Promise.reject('error')
        }
      },
      (err: AxiosError) => {
        console.log(err)
        if (err?.message) {
          ElMessage({
            type: 'error',
            message: err.message || '请求错误',
          })
          return Promise.reject(err.message)
        }
        return Promise.reject(err?.message)
      },
    )
  }
  get(url: string, params?: IOParams, config?: AxiosRequestConfig): Promise<IOResponse> {
    let paramStr = ''
    if (params && Object.keys(params)) {
      if (Object.prototype.toString.call(params) === '[object Object]') {
        paramStr = qs.stringify(params)
      } else {
        throw TypeError('axios.get params is not Object')
      }
    }
    return this.axiosInstance.get(url + (paramStr ? `?${paramStr}` : ''), config)
  }
  post(url: string, data: object, config?: AxiosRequestConfig): Promise<IOResponse> {
    return this.axiosInstance.post(url, data, config)
  }
  delete(url: string, config?: AxiosRequestConfig): Promise<IOResponse> {
    return this.axiosInstance.delete(url, config)
  }
  put(url: string, data: object, config?: AxiosRequestConfig): Promise<IOResponse> {
    return this.axiosInstance.put(url, data, config)
  }
}

const defaultConfig = {
  baseURL: import.meta.env.VITE_APP_MODE === 'dev' ? '/api' : import.meta.env.VITE_APP_SERVICE, // '/api', // import.meta.env.VITE_APP_SERVICE,
  timeout: 60 * 1000,
  headers: {
    'Content-Type': 'application/json',
  },
}
export default new AxiosHttp(defaultConfig)
